package stdio.costa.imoca.api;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import stdio.costa.imoca.spi.PostcardFrontSpi;

import com.sun.jersey.multipart.BodyPartEntity;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataParam;

@Path("/postcard_front")
@Component
@Scope("request")
public class PostcardFrontResource {

	@Autowired
	private PostcardFrontSpi postcardFrontSpi;

	@Path("/create")
	@POST
	@Produces({ "application/json;qs=1", "application/xml;qs=.5" })
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Transactional
	public void createPostFront(
			@FormDataParam("wish_picture") FormDataBodyPart bodyPart,
			@FormDataParam("access_token") String accessTokenCode,
			@FormDataParam("postcode") String postcode,
			@FormDataParam("receiver_address") String receiverAddress,
			@FormDataParam("sender_address") String senderAddress,
			@FormDataParam("sender_postcode") String senderPostcode)
			throws Exception {

		String[] codes = new String[postcode.length()];

		//please ignore this
		for (int index = 0; index < postcode.length(); index++) {
			codes[index] = postcode.substring(index, index + 1);
		}

		BodyPartEntity entity = (BodyPartEntity) bodyPart.getEntity();

		Image image = postcardFrontSpi.createPostcardFront(entity.getInputStream(), codes[0],
				codes[1], codes[2], codes[3], codes[4], codes[5],
				receiverAddress, senderAddress, senderPostcode);
		
		ImageIO.write((RenderedImage) image, "jpg", new File("c:\\uuid.jpg"));
	}
}